package library.and.xps.com.step.view.activity;

import android.content.Intent;
import android.support.design.widget.Snackbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jude.utils.JUtils;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.ListHolder;
import com.orhanobut.dialogplus.OnItemClickListener;
import com.orhanobut.dialogplus.ViewHolder;
import com.orhanobut.logger.Logger;
import com.squareup.okhttp.Request;
import com.zhy.autolayout.AutoLinearLayout;

import org.greenrobot.eventbus.EventBus;

import library.and.xps.com.step.R;
import library.and.xps.com.step.URLConstants;
import library.and.xps.com.step.adapter.DepartmentsInJoinTeamAdapter;
import library.and.xps.com.step.m.model.ChangeTeam;
import library.and.xps.com.step.m.model.CheckJoinTeamPassRes;
import library.and.xps.com.step.m.model.JoinTeamRes;
import library.and.xps.com.step.m.model.RequestParams;
import library.and.xps.com.step.m.netapi.OkHttpClientUtils;
import library.and.xps.com.step.net.ResponceWrapper;
import library.and.xps.com.step.util.AppCommond;
import library.and.xps.com.step.util.CommonUtils;
import library.and.xps.com.step.util.HttpResponsHelper;
import library.and.xps.com.step.util.RequestCallback;
import library.and.xps.com.step.view.base.BaseActivity;

public class JoinTeamCompleteActivity extends BaseActivity implements com.orhanobut.dialogplus.OnClickListener {
    CheckJoinTeamPassRes joinRes;

    TextView tv_department;
    Button bt_join;
    ImageView iv_back;
    EditText et_name, et_email;
    AutoLinearLayout al_department_choose;
    int selectedDepartmentId = 0;
    int teamId = 0;
    private final String REQUEST_JOINTEAM = "REQUEST_JOINTEAM";
    private final String REQUEST_CHANGETEAM = "REQUEST_CHANGETEAM";

    @Override
    protected int getLayout() {
        return R.layout.activity_jointeam_complete;
    }

    @Override
    protected void setData() {
        Intent intent = getIntent();
        joinRes = (CheckJoinTeamPassRes) intent.getSerializableExtra(JoinTeamActivity.ALLOWJOINTEAM);
        if (joinRes == null) return;

        CheckJoinTeamPassRes.ListBean bean = joinRes.getList().get(0);
        teamId = bean.getTeamid();
        selectedDepartmentId = bean.getDepartmentid();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        OkHttpClientUtils.cancelCall(REQUEST_CHANGETEAM);
        OkHttpClientUtils.cancelCall(REQUEST_JOINTEAM);
    }

    void showdialog(String hintText) {
        ViewHolder headerViewHolder = new ViewHolder(getLayoutInflater().inflate(R.layout.header, null));
        View headerView = headerViewHolder.getInflatedView();

        ((TextView) headerView.findViewById(R.id.tv_hint)).setText(hintText);
        DialogPlus dialog = DialogPlus.newDialog(this)
                .setContentHolder(new ListHolder())
                .setGravity(Gravity.CENTER)
                .setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(DialogPlus dialog, Object item, View view, int position) {
                        CheckJoinTeamPassRes.ListBean l = (CheckJoinTeamPassRes.ListBean) item;
                        tv_department.setText(l.getDName());
                        selectedDepartmentId = l.getDepartmentid();
                        dialog.dismiss();
                    }
                })
                .setInAnimation(R.anim.dialog_in_anim)
                .setOutAnimation(R.anim.dialog_out_anim)
                .setAdapter(new DepartmentsInJoinTeamAdapter(this, joinRes.getList()))
                .setOnClickListener(this)
                .setExpanded(true,700)
                .setHeader(headerView)
                .create();
        dialog.show();
    }

    void requestJointeam() {
        String json = RequestParams.getNewInstance()
                .setUserid(getUser().getUserid())
                .setTeamid(teamId + "")
                .setIntname(et_name.getText().toString())
                .setDepartmentid(selectedDepartmentId + "")
                //.setEmail(et_email.getText().toString()).getJson()
                .toString();

        OkHttpClientUtils.postJsonStringAsync(this, URLConstants.TEAM.JoinTeam, json, new RequestCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                dissmisDialog();
            }

            @Override
            public void onResponse(ResponceWrapper response) {
                dissmisDialog();

                String json = response.getBody();
                Logger.json(json);
                JoinTeamRes joinTeamRes = new Gson().fromJson(json, JoinTeamRes.class);

                if (HttpResponsHelper.SuccessResponce(joinTeamRes)) {
                    if (joinTeamRes.getObj().getNumber() == 1) {
                        changeToCurrentTeam();
                    } else {
                        CommonUtils.showCompleteDialog(JoinTeamCompleteActivity.this, JoinTeamCompleteActivity.this, "是否切换到此团队?");
                    }
                }
            }

            @Override
            public void onStart() {
                showDialog();
            }
        }, REQUEST_JOINTEAM);
    }

    void changeToCurrentTeam() {
        String data = URLConstants.TEAM.ChangeTeam + "?userid=" + getUser().getUserid() + "&teamid=" + teamId;
        OkHttpClientUtils.getDataAsync(this, data, new RequestCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                dissmisDialog();
            }

            @Override
            public void onResponse(ResponceWrapper response) {
                dissmisDialog();
                ChangeTeam changeTeam = new Gson().fromJson(response.getBody(), ChangeTeam.class);

                if (HttpResponsHelper.SuccessResponce(changeTeam)) {
                    JUtils.Toast("切换团队成功!");
                    closePreviousPages();
                } else {
                    JUtils.Toast("切换团队失败!");
                }
            }

            @Override
            public void onStart() {
                showDialog();
            }
        }, REQUEST_CHANGETEAM);
    }

    /**
     * 在这里关闭之前的页面
     */
    void closePreviousPages() {
        finish();
        AppCommond appCommond = new AppCommond.Builder()
                .setOpration(AppCommond.CLOSE_ACTIVITY)
                .setRequestcloseAcname("JoinTeamActivity", "SearchActivity")
                .build();

        EventBus.getDefault().post(appCommond);
    }

    @Override
    protected void init() {
        bt_join = r2v(R.id.bt_join);
        et_name = r2v(R.id.et_name);
        et_email = r2v(R.id.et_email);
        iv_back = r2v(R.id.actionbar_iv_back);
        iv_back.setOnClickListener(this);
        tv_department = r2v(R.id.tv_department);
        al_department_choose = r2v(R.id.al_department_choose);
        bt_join.setOnClickListener(this);
        al_department_choose.setOnClickListener(this);
        ((TextView)r2v(R.id.actionbar_tv_title)).setText("加入团队");
        r2v(R.id.actionbar_iv_back).setOnClickListener(this);
        r2v(R.id.actionbar_iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onClick(DialogPlus dialog, View view) {
        dialog.dismiss();
        switch (view.getId()) {
            case R.id.bt_join:
                JUtils.closeInputMethod(this);
                if (ableJoin()) {
                    requestJointeam();
                }
                break;
            case R.id.al_department_choose:
                showdialog("选择部门:");
                break;
            case R.id.actionbar_iv_back:
                finish();
                break;
            case R.id.footer_confirm_button:
                changeToCurrentTeam();
                break;
            case R.id.footer_close_button:
                closePreviousPages();
                break;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_join:
                if (ableJoin()) {
                    requestJointeam();
                }
                break;
            case R.id.al_department_choose:
                showdialog("选择部门:");
                break;
        }
    }

    boolean ableJoin() {
        if (teamId == 0 || selectedDepartmentId == 0) {
            Snackbar.make(bt_join, "错误", Snackbar.LENGTH_LONG)
                    .setAction("确定", null).show();
            return false;
        } else if (TextUtils.isEmpty(et_name.getText().toString())) {
            Snackbar.make(bt_join, "请输入昵称", Snackbar.LENGTH_LONG)
                    .setAction("确定", null).show();
            return false;
        }

        /**
         *  else if (TextUtils.isEmpty(et_email.getText().toString())) {
         Snackbar.make(bt_join, "请输入邮箱地址", Snackbar.LENGTH_LONG)
         .setAction("确定", null).show();
         return false;
         }
         * */

        return true;
    }
}
